package com.omg.server.service;

import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;
import java.util.ResourceBundle;

import org.apache.log4j.LogManager;
import org.apache.log4j.xml.DOMConfigurator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.omg.server.util.PropertiesHelper;
import com.omg.util.ApplicationContextUtil;

public class InitServerService {

	public static void initApp() {
		ResourceBundle bundle = ResourceBundle.getBundle("META-INF.config.env.application");
		Properties props = new Properties();
	    Enumeration<String> enums = bundle.getKeys();
	    String key = null;
	    String value = null;
	    while (enums.hasMoreElements()) {
	      key = enums.nextElement();
	      value = bundle.getString(key);
	      props.put(key, value);
	    }
	    //默认加载application.properties并存在内存中
	    PropertiesHelper.initDefaultProps(props);
		//初始化系统使用的Spring ApplicationContext
		ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
		ApplicationContextUtil.initApplicationContext(appContext);
		
		
		//初始化完成 Log4J
		initLog4J();
	}
	
	public static void initLog4J(){
		String log4jCfgPath = "/META-INF/config/log/log4j.xml";
		//首先检查是否已经有其他的log4j的配置文件和环境存在，比如jboss服务器自带的log4j配置会和当前应用发生冲突。
		String log4jConfigPath = System.getProperty("log4j.configuration"); 
		if (log4jConfigPath != null && log4jConfigPath.length() > 0) {
			LogManager.resetConfiguration();
		    System.out.println("==== 已经有的配置为Log4J ConfigFile: " + log4jConfigPath);
		}
		
		//String log4jCfgAbsPath = CommonUtil.getAppPath() + log4jCfgPath; //绝对路径
		URL log4jCfgAbsPathURL = InitServerService.class.getResource(log4jCfgPath); //绝对路径
		String log4jCfgAbsPath = log4jCfgAbsPathURL.getPath();
		System.setProperty("org.apache.commons.logging.LogFactory", "org.apache.commons.logging.impl.LogFactoryImpl");
		System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");
		System.setProperty("log4j.configuration", log4jCfgAbsPath);
		DOMConfigurator.configure(log4jCfgAbsPathURL);
		System.out.println("Log4j初始化完成.......");
	}
}
